<template>
  <a-layout class="login-layout">
    <a-card class="login-card" :body-style="{padding:'32px'}" :bordered="false">
      <div class="login-header">
        <a-typography-title :level="2">管理中心登录</a-typography-title>
        <a-typography-text>欢迎使用万维OPM企业ERP系统</a-typography-text>
      </div>
      <a-form :rules="rules" :model="form" @finish="login">
        <a-form-item name="mobile">
          <a-input size="large"
                   v-model:value="form.mobile"
                   placeholder="请输入手机号码"
                   allow-clear>
            <template #prefix><user-outlined/></template>
          </a-input>
        </a-form-item>
        <a-form-item name="password">
          <a-input-password size="large"
                            v-model:value="form.password"
                            placeholder="请输入密码"
                            allow-clear>
            <template #prefix><lock-outlined/></template>
          </a-input-password>
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="14">
            <a-form-item name="captcha">
              <a-input size="large" v-model:value="form.captcha" placeholder="请输入验证码">
                <template #prefix><VerifiedOutlined/></template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-tooltip title="点击刷新">
              <div class="captcha-image" @click="refreshCaptcha">
                <div class="spin-inner" v-if="imageLoading">
                  <a-spin :spinning="imageLoading"/>
                </div>
                <img :src="captchaImage" alt="captcha" v-else>
              </div>
            </a-tooltip>
          </a-col>
        </a-row>
        <a-form-item>
          <a-flex justify="space-between">
            <span>
              <a-checkbox v-model:checked="form.remember">自动登录</a-checkbox>
            </span>
            <router-link to="/login">忘记密码？</router-link>
          </a-flex>
        </a-form-item>
        <a-form-item>
          <a-button size="large"
                    @click="login"
                    type="primary"
                    html-type="submit"
                    :loading="loading" block>登录</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </a-layout>

</template>

<script setup lang="ts">
import {UserOutlined,LockOutlined,VerifiedOutlined} from "@ant-design/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {getCaptcha, userLogin} from "@/api/modules/user";
import {useDebounce} from "@/plugin/useFn";
import useMessage from "@/plugin/useMessage";
import {useRouter} from "vue-router";
import useStorage from "@/plugin/useStorage";
import {useUserStore} from "@/store/user";

interface formState {
  mobile: number | string,
  password: string,
  captcha:string,
  hash:string,
  remember: boolean,
  login_type: string
}
let captchaImage = ref<string>(''),
    loading = ref<boolean>(false),
    imageLoading = ref<boolean>(true)

const store = useUserStore()
const router = useRouter()

const form = reactive<formState>({
  mobile: '',
  password: '',
  remember: true,
  login_type: 'account',
  hash:'',
  captcha:''
})
const rules = {
  mobile: [
    {required: true, message: '手机号不能为空',trigger:'blur'},
    {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误',trigger:'blur'}
  ],
  password: [
    {required: true, message: '账户密码不能为空',trigger:'blur'},
    {min: 6, max: 18, message: '密码为6-18位',trigger:'blur'}
  ],
  captcha: [
    {required: true, message: '验证码不能为空', trigger: 'blur'},
    {len: 4, message: '验证码为四位数，不区分大小写',trigger: 'blur'},
  ]
}

///异步获取验证码图片
const getCaptchaImage = async () => {
  // 开始加载验证码图片，设置加载状态为true
  imageLoading.value = true
  // 等待获取验证码的异步操作
  let res = await getCaptcha()
  if(res){
    // 设置验证码加载完成后的延迟处理，200毫秒后将加载状态设置为false
    setTimeout(()=>imageLoading.value = false,200)
    // 更新验证码图片的URL
    captchaImage.value = res.data.image
    // 更新表单中的hash值，用于验证
    form.hash = res.data.hash
  }
}

// 防抖 刷新验证码
const refreshCaptcha = useDebounce(()=>getCaptchaImage(),200)
onMounted(()=>{
  getCaptchaImage()
})

/**
 * 异步登录函数，根据用户提供的表单值进行登录操作。
 * @param values
 */
const login = async (values:formState)=>{
  if(values.mobile){
    // 显示加载状态
    loading.value = true
    // 5秒后隐藏加载状态
    setTimeout(()=>loading.value = false,5000)
    // 执行用户登录操作
    let res:any = await userLogin(form)
    // 登录成功后的处理逻辑
    if(res.code === 200){
      //写入用户信息到pinia
      store.setUserInfo(res.data)
      // 2秒后跳转到管理中心首页
      setTimeout(()=> router.push('/'),2000)
    }else{
      // 登录失败，刷新验证码
      refreshCaptcha()
    }
    useMessage(res.code, res.message)
  }
}

</script>

<style scoped>
.login-layout{
  min-height: 100vh;
  display: flex;
  align-items: center;
  padding-top: 100px;
}
.login-card{
  width: 360px;
}
.login-header {
  margin-bottom: 24px;
  text-align: center;
}
.captcha-image {
  width: 100%;
  height: 40px;
  border-radius: var(--radius);
  overflow: hidden;
  border:1px solid #d9d9d9
}
.captcha-image:hover{
  cursor: pointer;
  border-color: #4096ff;
  transition: var(--transition);
}
.spin-inner {
  text-align: center;
  padding-top: 8px;
}
</style>